unity3d sqlite数据库的读写方法

  首先,我们要从unity的安装路径中复制mono.data.sqlite.dll和sqlite3.dll两个动态链接库到untiy的plugins目录下,如下图所示:

使用navicat for sqlite创建一个sqlite数据库文件,放到Resources文件夹目录中,如下图所示:

新建一个DbAccess脚步,添加以下脚步:

using UnityEngine;

using System;

using System.Collections;

using Mono.Data.Sqlite;

using System.IO;

 

public class DbAccess  {

    private SqliteConnection dbConnection;//sql连接

    private SqliteCommand dbCommand=null;//sql命令

    private SqliteDataReader dbReader;//sql读取器

 

    public DbAccess(string connectionString)

    {

        string appDBPath = "";

 

        if(Application.platform == RuntimePlatform.WindowsEditor)//如果是windows编辑器中

        {

             appDBPath = Application.dataPath+"//"+connectionString;

        }

        else if(Application.platform == RuntimePlatform.Android)--如果是安卓平台

        {

            appDBPath = Application.persistentDataPath +"/" + connectionString;

            if (!File.Exists(appDBPath))

            {

                WWW loader = new WWW("jar:file://" + Application.dataPath + "/" + connectionString);//把数据库复制到安卓可写路径中,注:sqlite不能在安装包中读取数据

                File.WriteAllBytes(appDBPath,loader.bytes);

            }

        }

        OpenDB("Data Source="+appDBPath);

    }

 

    private void OpenDB(string connectionString)

    {

        try

        {

            dbConnection = new SqliteConnection(connectionString);

            dbConnection.Open();

            Debug.Log("connect to db");

        }

        catch (System.Exception ex)

        {

            Debug.Log(ex.Message);

        }

    }

 

    public void CloseSqlConnection()//关闭数据库连接

    {

        if (dbCommand!=null)

            dbCommand.Dispose();

        dbCommand = null;

 

        if (dbReader!=null)

            dbReader.Dispose();

        dbReader = null;

 

        if (dbConnection!=null)

            dbConnection.Close();

        dbConnection = null;

    }

 

    public SqliteDataReader ExecuteQuery(string sqlQuery)//执行查询

    {

        dbCommand = dbConnection.CreateCommand();

        dbCommand.CommandText = sqlQuery;

        dbReader = dbCommand.ExecuteReader();

        return dbReader;

    }

 

    public SqliteDataReader ReadFullTable(string tableName)//读取整个表

    {

        string query = "SELECT * FROM " + tableName+";";

        return ExecuteQuery(query);

    }

 

    public SqliteDataReader InsertInto(string tableName,string[] values)//在表中插入数据

    {

        string query = "INSERT INTO " + tableName + " VALUES('" + values[0];

        for (int i = 1; i < values.Length;i++ )

        {

            query += "','" + values[i];

        }

        query += "')";

        return ExecuteQuery(query);

    }

 

    public SqliteDataReader UpdateInto(string tableName,string[] cols,string colsValues,string selectKey,string selectValue)//替换表中数据

    {

        string query = "UPDATE " + tableName + " SET " + cols[0] + " = " + colsValues[0];

 

        for (int i = 1; i < colsValues.Length; ++i)

        {

 

            query += ", " + cols[i] + " =" + colsValues[i];

        }

 

        query += " WHERE " + selectKey + " = " + selectValue + " ";

        return ExecuteQuery(query);

    }

 

    public SqliteDataReader Delete(string tableName, string[] cols, string[] colsvalues)//删除表中数据

    {

        string query = "DELETE FROM " + tableName + " WHERE " + cols[0] + " = " + colsvalues[0];

 

        for (int i = 1; i < colsvalues.Length; ++i)

        {

 

            query += " or " + cols[i] + " = " + colsvalues[i];

        }

        return ExecuteQuery(query);

    }

 

    public SqliteDataReader InsertIntoSpecific (string tableName, string[] cols, string[] values)//插入特定值

    {

        if (cols.Length != values.Length) {

 

            throw new SqliteException ("columns.Length != values.Length");

        }

 

        string query = "INSERT INTO " + tableName + "(" + cols[0];

 

        for (int i = 1; i < cols.Length; ++i) {

 

            query += ", " + cols[i];

 

        }

 

        query += ") VALUES (" + values[0];

 

        for (int i = 1; i < values.Length; ++i) {

 

            query += ", " + values[i];

 

        }

 

        query += ")";

 

        return ExecuteQuery (query);

 

    }

 

    public SqliteDataReader DeleteContents (string tableName)//删除表

    {

        string query = "DELETE FROM " + tableName;

 

        return ExecuteQuery (query);

 

    }

 

    public SqliteDataReader CreateTable (string name, string[] col, string[] colType)//创建表

    {

        if (col.Length != colType.Length) {

 

            throw new SqliteException ("columns.Length != colType.Length");

 

        }

 

        string query = "CREATE TABLE " + name + " (" + col[0] + " " + colType[0];

 

        for (int i = 1; i < col.Length; ++i) {

 

            query += ", " + col[i] + " " + colType[i];

 

        }

 

        query += ")";

 

        return ExecuteQuery (query);

 

    }

 

    public SqliteDataReader SelectWhere (string tableName, string[] items, string[] col, string[] operation, string[] values)//集成所有操作后执行

    {

        if (col.Length != operation.Length || operation.Length != values.Length) {

            throw new SqliteException ("col.Length != operation.Length != values.Length");

        }

 

        string query = "SELECT " + items[0];

 

        for (int i = 1; i < items.Length; ++i) {

 

            query += ", " + items[i];

 

        }

 

        query += " FROM " + tableName + " WHERE " + col[0] + operation[0] + "'" + values[0] + "' ";

 

        for (int i = 1; i < col.Length; ++i) {

 

            query += " AND " + col[i] + operation[i] + "'" + values[0] + "' ";

 

        }

 

        return ExecuteQuery (query);

 

    }

 

}

 

使用事例:

数据库的Dialog表中有一下数据:

 

        DbAccess db = new DbAccess("/Resources/DazzleParkour.sqlite");

 

        using (SqliteDataReader reader = db.SelectWhere("Dialog", new string[] { "id,Name,FileName,Scale" }, new string[] { "Scale" }, new string[] { "=" }, new string[] { "1" }))//读取出Scale等于1的数据

 

        {

 

            while (reader.Read())// 循环遍历数据

 

            {

 

                int name = reader.GetInt32(reader.GetOrdinal("id"));

 

                Debug.Log(name);

 

            }

 

            reader.Close();

 

            db.CloseSqlConnection();

 

        }

 

最后打印的数据如下

 

在打包时,注意要把playersetting里的api解析等级改为.Net 2.0

posted on 2015-10-01 10:32  HemJohn  阅读(6040)  评论(0编辑  收藏  举报

导航